#include "networkjsonresponse.h"
#include <json.h>

#include <QTextStream>


namespace Network {

JSONResponse::JSONResponse(QObject *parent)
    : Response(parent)
{
}

void JSONResponse::parse(const QByteArray &data)
{
    JsonReader reader;
    QVariant variant;
    QTextStream stream(data);
    stream.setCodec("UTF-8");
    if (!reader.read(stream, variant)) {
        setError(Response::Syntax, "JSON text error");
       // emit onChanned();
        return;
    }
    if (variant.type() != QVariant::Map) {
        setError(Response::Property, "Missing the properties map");
        return;
    }
    QVariantMap map = variant.toMap();
    if (!map.contains("error_code")) {
        setError(Response::Property, "Missing the error code field");
        return;
    }

    QVariant errorCode = map.value("error_code");
    if (errorCode.type() != QVariant::Int) {
        setError(Response::Property, "The error code field incompatitive");
        return;
    }

    if (errorCode.toInt() != 0){
        QVariant message = map.value("error_message");
        setError(Response::Property, message.toString(), errorCode.toInt());
        return;
    }


    if (!map.contains("data")) {
        setError(Response::Property, "The error code field is missed");
        return;
    }

    // update status, profile data can return null
    QVariant properties = map.value("data");
    if (properties.isNull()) {
        setError(Response::Property, "The error code field is invalied");
        return;
    }

    parse(properties);
}


} // namespace Network
